package com.gmall.java;

import com.gmall.java.model.CityDTO;
import com.gmall.java.model.CityEntity;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamTestTree {

    public static void main(String[] args) {
        /** id  name         parent_id
         *  1 山西           0
         *  2     运城       1
         *  4        临猗    2
         *  5        永济    2
         *  3     长治       1
         *  6        沁县    3
         *  7        武乡    3
         *  8 河南           0
         */
        List<CityEntity> cityEntities = new ArrayList<>();
        cityEntities.add(new CityEntity(1,0,"山西"));
        cityEntities.add(new CityEntity(2,1,"运城"));
        cityEntities.add(new CityEntity(3,1,"长治"));
        cityEntities.add(new CityEntity(4,2,"临猗"));
        cityEntities.add(new CityEntity(5,2,"永济"));
        cityEntities.add(new CityEntity(6,3,"沁县"));
        cityEntities.add(new CityEntity(7,3,"武乡"));
        cityEntities.add(new CityEntity(8,0,"河南"));

        List<CityDTO> collect = cityEntities.stream()
                .filter(cityEntity -> cityEntity.getParentId() == 0)
                .map(cityEntity -> {
                    CityDTO cityDTO = new CityDTO();
                    BeanUtils.copyProperties(cityEntity, cityDTO);
                    cityDTO.setChildren(getChildren(cityEntities,cityEntity.getId()));
                    return cityDTO;
                })
                .collect(Collectors.toList());
    }

    public static List<CityDTO> getChildren(List<CityEntity> cityEntities,Integer id ) {

        List<CityDTO> collect = cityEntities.stream()
                .filter(cityEntity -> {
                    return cityEntity.getParentId().equals(id);
                })
                .map(cityEntity -> {
                    CityDTO cityDTO = new CityDTO();
                    BeanUtils.copyProperties(cityEntity, cityDTO);
                    cityDTO.setChildren(getChildren(cityEntities, cityEntity.getId()));
                    return cityDTO;
                }).collect(Collectors.toList());

        if(collect.size() == 0){
            return null;
        }
        return collect;
    }
}
